#include "precompiled.h"
#include "optimizationfactory.h"
using namespace weo::engine::optimization;
OptimizationFactory *OptimizationFactory::s_Factory = NULL;
void* OptimizationFactory::callFactory(std::string name, unsigned int count)
{
    std::map<std::string,OptimizationFactoryFn*>::iterator it = m_OptimizerMap.find(name);
    std::map<unsigned int,std::string>::iterator it2;
    if(it != m_OptimizerMap.end())
    {
        return it->second();
    }
    else 
    {
        std::map<unsigned int,std::string>::iterator itfound = m_PerformanceMap.end();
        double itemcount = (count == 0) ? m_Itemscount : (double) count;
        for(it2 = m_PerformanceMap.begin();it2 != m_PerformanceMap.end();it2++)
        {
            if(it2->first <= itemcount)
            {
                itfound = it2;
            }
            else
            {
                if(itfound != m_PerformanceMap.end())
                {
                    break;
                }
                else
                {
                    itfound = it2;
                }
            }
        }
        if(itfound != m_PerformanceMap.end())
        {
            return m_OptimizerMap.find(itfound->second)->second();
        }
    }
    return NULL;
}
void OptimizationFactory::registerOptimizer(std::string name, unsigned int count, OptimizationFactoryFn* pFunction)
{
    std::map<std::string,OptimizationFactoryFn*>::iterator it = m_OptimizerMap.find(name);
    if(it == m_OptimizerMap.end())
    {
        m_OptimizerMap[name] = pFunction;
        m_PerformanceMap[count] = name;
    }	
}
OptimizationFactory::OptimizationFactory()
{
    memset(m_Locks,0,weo::engine::Slotcount*sizeof(bool));
}
OptimizationFactory* OptimizationFactory::getInstance()
{
    if(!s_Factory)
    {
        s_Factory = new OptimizationFactory();
    }
    return s_Factory;
}